Page({
  data: {
      imagePath: '', // 上传的图片路径
      processedImage: '', // 处理后的图片路径
      whitening: 0, // 美白强度 (0-100)
      brightness: 0, // 亮度 (-100-100)
      contrast: 0, // 对比度 (-100-100)
      saturation: 0, // 饱和度 (-100-100)
      sharpen: 0, // 锐化 (0-100)
      isProcessing: false // 是否正在处理中
  },

  // 选择图片
  chooseImage: function () {
      const that = this;
      wx.chooseImage({
          count: 1,
          sizeType: ['original', 'compressed'],
          sourceType: ['album', 'camera'],
          success(res) {
              that.setData({
                  imagePath: res.tempFilePaths[0],
                  processedImage: ''
              });
          }
      });
  },

  // 参数变化处理
  onWhiteningChange: function (e) {
      this.setData({
          whitening: e.detail.value
      });
  },

  onBrightnessChange: function (e) {
      this.setData({
          brightness: e.detail.value
      });
  },

  onContrastChange: function (e) {
      this.setData({
          contrast: e.detail.value
      });
  },

  onSaturationChange: function (e) {
      this.setData({
          saturation: e.detail.value
      });
  },

  onSharpenChange: function (e) {
      this.setData({
          sharpen: e.detail.value
      });
  },

  // 处理图片
  processImage: function () {
      const that = this;
      wx.showLoading({
          title: '处理中...'
      });

      // 确保使用数值而不是字符串
      const formData = {
          brightness_strength: String((Number(this.data.brightness) / 100) * 20),
          contrast_strength: String((Number(this.data.contrast) / 100) * 20),
          sharpen_strength: String((Number(this.data.sharpen) / 100) * 2),
          saturation_strength: String((Number(this.data.saturation) / 100) * 2),
          whitening_strength: String((Number(this.data.whitening) / 100) * 10),
          height: '413',
          width: '295',
          human_matting_model: 'modnet_photographic_portrait_matting',
          face_detect_model: 'mtcnn',
          hd: 'true',
          dpi: '300',
          face_alignment: 'true',
          head_measure_ratio: '0.2',
          head_height_ratio: '0.45',
          top_distance_max: '0.12',
          top_distance_min: '0.1'
      };

      console.log('实际发送的参数:', formData); // 调试用

      wx.uploadFile({
          url: 'http://127.0.0.1:8080/idphoto',
          filePath: this.data.imagePath,
          name: 'input_image',
          formData: formData,
          success(res) {
              wx.hideLoading();
              try {
                  const data = JSON.parse(res.data);
                  console.log('API返回数据:', data); // 调试用

                  if (data.image_base64_standard) {
                      // 处理可能的base64前缀问题
                      let base64Data = data.image_base64_standard;
                      if (!base64Data.startsWith('data:image')) {
                          base64Data = 'data:image/png;base64,' + base64Data;
                      }

                      that.setData({
                          processedImage: base64Data + '?t=' + Date.now()
                      });
                  }
              } catch (e) {
                  console.error('解析响应失败:', e, '原始数据:', res.data);
                  wx.showToast({
                      title: '处理失败',
                      icon: 'none'
                  });
              }
          },
          fail(err) {
              wx.hideLoading();
              console.error('请求失败:', err);
              wx.showToast({
                  title: '请求失败',
                  icon: 'none'
              });
          }
      });
  },



  saveImage() {
      const {
          processedImage
      } = this.data;
      if (!processedImage) return;

      // 处理Base64数据 - 移除可能的重复前缀
      let base64Data = processedImage;
      if (base64Data.includes(':image/png;base64,')) {
          base64Data = base64Data.replace(':image/png;base64,', 'data:image/png;base64,');
      } else if (base64Data.startsWith('data:image/png;base64,')) {
          // 已经是正确格式，不做处理
      } else {
          // 如果没有前缀，添加标准前缀
          base64Data = `data:image/png;base64,${base64Data}`;
      }

      // 生成临时文件路径
      const filePath = `${wx.env.USER_DATA_PATH}/temp_${Date.now()}.png`;

      wx.showLoading({
          title: '保存中...'
      });
      wx.getFileSystemManager().writeFile({
          filePath,
          data: base64Data.split(',')[1], // 确保只取逗号后的部分
          encoding: 'base64',
          success: () => {
              wx.saveImageToPhotosAlbum({
                  filePath,
                  success: () => {
                      wx.showToast({
                          title: '保存成功'
                      });
                  },
                  fail: (err) => {
                      console.error('保存失败:', err);
                      wx.showToast({
                          title: '保存失败，请检查权限设置',
                          icon: 'none'
                      });
                  }
              });
          },
          fail: (err) => {
              console.error('文件写入失败:', err);
              wx.showToast({
                  title: '图片格式错误',
                  icon: 'none'
              });
          },
          complete: () => wx.hideLoading()
      });

      console.log('Base64数据前100字符:', base64Data.substring(0, 100));
  }
});